package cn.shop.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.util.StrUtil;
import cn.shop.front.service.BankCardService;
import cn.shop.front.service.FrontUserService;
import cn.shop.front.util.CurrentUserUtil;
import cn.shop.thiredparty.entity.AuthResult;
import cn.shop.thiredparty.entity.BankAuthCode;
import cn.shop.thiredparty.service.ThiredpartyService;
import cn.shop.transcation.bankcard.entity.BankAndIDInfo;
import cn.shop.transcation.bankcard.entity.BankCard;
import cn.shop.transcation.frontUserModule.FrontUser;
import cn.shop.utils.ApiCode;
import cn.shop.utils.ApiResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 银行卡绑定接口
 * @author : 李一涵
 * @date : Created in 2022-2-16 14:58
 * @description :
 */
@Slf4j
@SaCheckLogin
@RestController
@RequestMapping("/api/v1/bankcard")
public class BankCardController {

    @Resource
    private BankCardService bankCardService;
    @Resource
    private ThiredpartyService thiredpartyService;
    @Resource
    private FrontUserService frontUserService;

    private static final int MAX_BANK_COUNT = 5;

    /**
     * 保存银行卡
     * @param bankCard 银行卡信息
     * @return 返回结果
     */
    @PostMapping("")
    public ApiResult<Map<String, Object>> save(@Validated @RequestBody BankCard bankCard) {
        long ownerId = CurrentUserUtil.getUserId();
        long count = bankCardService.getBankCount(ownerId);
        if (count >= MAX_BANK_COUNT) {
            return ApiResult.fail(ApiCode.FAIL, "银行卡最多只能添加5个");
        }
        FrontUser user = frontUserService.getById(ownerId);
        if (user == null || StrUtil.isBlank(user.getIdentityCard())) {
            return ApiResult.fail(ApiCode.NOT_REAL_NAME, "请先进行实名认证", null);
        }
        if (StrUtil.isBlank(user.getName())) {
            return ApiResult.fail("请先完善基本信息");
        }
        AuthResult result = thiredpartyService.bankAuth(bankCard.getCardNo(), user.getIdentityCard(), bankCard.getMobile(), user.getName());
        log.info("银行卡验证结果: {}", result);
        if (result == null) {
            log.error("银行卡认证接口失败，接口返回无结果");
            return ApiResult.fail("银行卡认证失败");
        }
        if (!BankAuthCode.C10000.code().equals(result.getCode())) {
            return ApiResult.fail("银行卡认证失败");
        }
        if (!AuthResult.State.SAME.code().equals(result.getData().getState())) {
            return ApiResult.fail("请检查银行卡信息是否正确");
        }
        bankCard.setName(user.getName());
        bankCard.setOwnerId(ownerId);
        //判断是否为第一张银行卡
        boolean isFirst = bankCardService.bankList(ownerId).size() == 0;
        if (isFirst){
            // 添加默认状态
            bankCard.setCardDefault(true);
        }
        return ApiResult.result(bankCardService.save(bankCard));
    }

    /**
     * 更新银行卡信息
     * @param bankCard 银行卡信息
     * @return 返回结果
     */
    @PutMapping("")
    public ApiResult<Map<String, Object>> update(@Validated @RequestBody BankCard bankCard) {
        long ownerId = CurrentUserUtil.getUserId();
        FrontUser user = frontUserService.getById(ownerId);
        if (StrUtil.isBlank(user.getName())) {
            return ApiResult.fail("请先完善基本信息");
        }
        if (!user.getCertification()) {
            return ApiResult.fail("请先实名认证");
        }
        AuthResult result = thiredpartyService.bankAuth(bankCard.getCardNo(), user.getIdentityCard(), bankCard.getMobile(), user.getName());
        if (!BankAuthCode.C10000.code().equals(result.getCode())) {
            return ApiResult.fail("银行卡认证失败");
        }
        if (!AuthResult.State.SAME.code().equals(result.getData().getState())) {
            return ApiResult.fail("请检查银行卡信息是否正确");
        }
        return ApiResult.result(bankCardService.updateInfo(ownerId, bankCard));
    }

    /**
     * 获取已绑定的银行卡列表
     * @return 返回结果
     */
    @GetMapping("")
    public ApiResult<List<Map<String, Object>>> list() {
        long ownerId = CurrentUserUtil.getUserId();
        List<Map<String, Object>> list = bankCardService.bankList(ownerId);
        return ApiResult.success(list);
    }

    /**
     * 获取银行卡信息
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public ApiResult<Map<String, Object>> info(@PathVariable long id) {
        return ApiResult.success(bankCardService.getInfo(id, CurrentUserUtil.getUserId()));
    }

    /**
     * 删除银行卡信息
     * @param id 编号
     * @return 返回结果
     */
    @DeleteMapping("/{id}")
    public ApiResult<Map<String, Object>> delete(@PathVariable long id) {
        BankCard delete = new BankCard();
        delete.setId(id);
        delete.setOwnerId(CurrentUserUtil.getUserId());
        return ApiResult.result(bankCardService.removeById(delete));
    }
    /**
     * 获取登录用户的银行卡信息实名信息和账号信息
     * @author 王鹤然
     * @date 2023/1/30 0030 上午 10:21
     * @return cn.shop.utils.ApiResult<java.util.Map<java.lang.String,java.lang.Object>>
    */
    @GetMapping("/getInfo")
    public ApiResult<BankAndIDInfo> bankAndIDInfo() {
        return ApiResult.success(bankCardService.getBankAndIDInfo(CurrentUserUtil.getUserId()));
    }
    /**
     *提交登录用户的银行卡信息实名信息和账号信息
     * @author 王鹤然
     * @date 2023/1/30 0030 上午 10:48
     * @param bankAndIDInfo
     * @return cn.shop.utils.ApiResult<java.util.Map<java.lang.String,java.lang.Object>>
    */
    @PostMapping("/submitBankAndID")
    public ApiResult<Map<String,Object>> submitBankAndID(@RequestBody BankAndIDInfo bankAndIDInfo) {
        return bankCardService.submitBankAndID(bankAndIDInfo);
    }
    /**
     * 修改默认银行卡
     * @author 王鹤然
     * @date 2023/1/30 0030 下午 14:58
     * @param bankCard
     * @return cn.shop.utils.ApiResult<java.util.Map<java.lang.String,java.lang.Object>>
    */
    @PutMapping("/changeDefault")
    public ApiResult<Map<String,Object>> changeDefault(@RequestBody BankCard bankCard) {
        return ApiResult.result(bankCardService.changeDefault(bankCard));
    }
}
